package cn.edu.hbwe.book.dao.impl;

import java.sql.Connection;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

import cn.edu.hbwe.book.dao.OrderItemDao;
import cn.edu.hbwe.book.entity.Book;
import cn.edu.hbwe.book.entity.Order;
import cn.edu.hbwe.book.entity.OrderItem;
import cn.edu.hbwe.book.utils.C3p0Util;
import cn.edu.hbwe.book.utils.DBCPUtil;

import cn.edu.hbwe.book.utils.DuridUtil;

public class OrderItemDaoImpl implements OrderItemDao{
	public List<OrderItem> findOrderItemByOrder(Order order) throws SQLException {
		//1.生成sql语句
		String sql = "select * from orderItem,Products where products.id=orderItem.product_id and order_id=?";
		//2.创建QueryRunner对象
		QueryRunner runner=new QueryRunner();
		Connection conn=DuridUtil.getConn();
		//3.返回QueryRunner对象query()方法的查询结果
		return runner.query(conn,sql, new ResultSetHandler<List<OrderItem>>() {
			public List<OrderItem> handle(ResultSet rs) throws SQLException {

				List<OrderItem> items = new ArrayList<OrderItem>();
				while (rs.next()) {
					OrderItem item = new OrderItem();

					item.setOrder(order);
					item.setBuynum(rs.getInt("buynum"));

					Book p = new Book();
					p.setCategory(rs.getString("category"));
					p.setId(rs.getString("id"));
					p.setDescription(rs.getString("description"));
					p.setImgurl(rs.getString("imgurl"));
					p.setName(rs.getString("name"));
					p.setPnum(rs.getInt("pnum"));
					p.setPrice(rs.getDouble("price"));
					item.setP(p);

					items.add(item);
				}
				return items;
			}
		}, order.getId());
	}
	//根据获取到的订单id删除订单
	public void delOrderItems(String id) throws SQLException {
		String sql="delete from orderItem where order_id=?";
		
		QueryRunner runner=new QueryRunner();
		Connection conn=DuridUtil.getConn();
		
		runner.update(conn,sql,id);
	}
	
	//添加订单
	public void addOrderItem(Order order) throws SQLException {
		// 1.生成sql语句
		String sql = "insert into orderItem values(?,?,?)";

		QueryRunner runner = new QueryRunner();
		Connection conn=DuridUtil.getConn();

		List<OrderItem> items = order.getOrderItems();

		//Object[][] params = new Object[items.size()][3];

		for (int i = 0; i < items.size(); i++) {
			runner.update(conn,sql,items.get(i).getOrder().getId(), items.get(i).getP().getId(),items.get(i).getBuynum());
		}

		
	}

}
